//
//  addActViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/10/6.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "addActViewController.h"
#import "webCollectionViewCell.h"
#import "VPImageCropperViewController.h"
#import "UpYun.h"
#import "RDVTabBarController.h"
#import "HZAreaPickerView.h"
#import "HAODEsingleton.h"

#import "TheLoginViewController.h"
#import "HttpRequest.h"
#import "UIButton+WebCache.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "ZJSwitch.h"
#import "actlistsViewController.h"
#import "PECropViewController.h"
@interface addActViewController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource, UITextViewDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate,UITextFieldDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,HZAreaPickerDelegate,VPImageCropperDelegate>
@property (strong, nonatomic) NSString *areaValue;
@property (strong, nonatomic) NSString*cityValue;
@property (strong, nonatomic) HZAreaPickerView *locatePicker;
@property(nonatomic,retain)UIDatePicker* da;
@property (nonatomic, strong) UIImageView *portraitImageView;
@property (nonatomic,strong) UIImagePickerController *ipc;
@property (strong, nonatomic) UIImage *sendImage;
@property (strong, nonatomic) NSString *sat;
@property (strong, nonatomic) NSString *companyImg;
@property (strong, nonatomic) NSString *companyImgWidth;
@property (strong, nonatomic) NSString *companyImgHeight;
@property (strong, nonatomic) NSString*bossIdCardImg;
@property (strong, nonatomic) NSString *bossIdCardImgWidth;
@property (strong, nonatomic) NSString *bossIdCardImgHeight;
@property (strong, nonatomic) NSString*businessLicenseImg;
@property (strong, nonatomic) NSString *businessLicenseImgWidth;
@property (strong, nonatomic) NSString *businessLicenseImgHeight;
@property (nonatomic,retain)NSString*jzdprovince;
@property (nonatomic,retain)NSString*jzdcity;
@property (nonatomic,retain)NSString*jzddistrict;
@property (nonatomic) UIPopoverController *popover;
@end

@implementation addActViewController

{
    UITextField*closeTimeTextFied;
    UITextField*openTimeTextFied;
    UITextField*titleTextField;
    UIScrollView*mainScroll;
    HAODEsingleton*commdity;
    UITextField*priceTextFied;
    UITextField*actAddressTextFied;
    UITextView*tv;
    UITextField*AddressTextFied;
    UITextField*leibieTextFied;
    UITextField*ownerCardNoTextFied;
    UITextField*urlTextField;
    UITextField*bossNameTextField;
    UITextField*endDateTextFied;
    UIButton*agreementBtn;
    UIButton*renzheng;
    BOOL saveAccount;
    UIImageView*imagess;
    UIButton*mendianimage;
    UIButton*farennimage;
    UIButton*yingyeimage;
    UIImage *image;
    NSString*isOpen;
    ZJSwitch *switch2;
    UILabel*labels;
    NSMutableArray *imageArray;
      NSMutableArray*imageList;
    UIImage *image1;
}

@synthesize alt = alt;
@synthesize areaValue=_areaValue, cityValue=_cityValue;
@synthesize locatePicker=_locatePicker;

-(void)setAreaValue:(NSString *)areaValue
{
    if (![_areaValue isEqualToString:areaValue]) {
        
        priceTextFied.text = areaValue;
        
    }
}

-(void)setCityValue:(NSString *)cityValue
{
    if (![_cityValue isEqualToString:cityValue]) {
        
        priceTextFied.text = cityValue;
    }
}

#pragma mark - HZAreaPicker delegate
-(void)pickerDidChaneStatus:(HZAreaPickerView *)picker
{
    if (picker.pickerStyle == HZAreaPickerWithStateAndCityAndDistrict) {
        self.areaValue = [NSString stringWithFormat:@"%@ %@ %@", picker.locate.state, picker.locate.city, picker.locate.district];
        
        
        self.jzdprovince= picker.locate.state;
        self.jzdcity=picker.locate.city;
        self.jzddistrict=picker.locate.district;
        
        
        
    } else{
        self.cityValue = [NSString stringWithFormat:@"%@ %@", picker.locate.state, picker.locate.city];
        
    }
}
-(void)area:(UIButton*)sender{
    
    
    [closeTimeTextFied resignFirstResponder];
    [openTimeTextFied resignFirstResponder];
    [titleTextField resignFirstResponder];
    [AddressTextFied resignFirstResponder];
    [priceTextFied resignFirstResponder];
    
    [tv resignFirstResponder];
    [actAddressTextFied resignFirstResponder];
    [urlTextField resignFirstResponder];
    [endDateTextFied resignFirstResponder];
    [self cancelLocatePicker];
    self.locatePicker = [[HZAreaPickerView alloc] initWithStyle:HZAreaPickerWithStateAndCityAndDistrict delegate:self] ;
    [self.locatePicker showInView:self.view];
    
     priceTextFied.text=@"北京 通州";
    
}

-(void)cancelLocatePicker
{
    [self.locatePicker cancelPicker];
    self.locatePicker.delegate = nil;
    self.locatePicker = nil;
}


#pragma mark - TextField delegate

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [self cancelLocatePicker];
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    commdity=[HAODEsingleton shared];
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden = NO;
        self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:@"other" forKey:@"uploadType"];
    
//  [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Common/GetUpyunFormParams" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                
                NSLog(@"%@",severDataDict.dataDict);
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSString*policy=[severDataDict.dataDict objectForKey:@"policy"];
                NSString*signature=[severDataDict.dataDict objectForKey:@"signature"];
                NSString*action=[severDataDict.dataDict objectForKey:@"action"];
                [user setObject:signature forKey:@"signature"];
                [user setObject:policy forKey:@"policy"];
                [user setObject:action forKey:@"action"];
                [user synchronize];
                
            }else{
                
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
    
    leibieTextFied.text=commdity.content;
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    self.title = @"添加活动";
    isOpen=@"0";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     backColor,
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    
    
    
    _da = [[UIDatePicker alloc] init];
    [_da addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
    _da.datePickerMode = UIDatePickerModeDate;
    _da.backgroundColor=[UIColor whiteColor];
    
    UIButton* baocun= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 30)];
    [baocun setTitle:@"保存" forState:UIControlStateNormal];
    [baocun setTitleColor:luseColor forState:UIControlStateNormal];
    [baocun addTarget:self action:@selector(add:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:baocun];
    self.navigationItem.rightBarButtonItem = leftBarButton;
    
    
    mainScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, ScreenHeight)];
    
    
    [mainScroll setBackgroundColor:zuiqianhuicolor];
    mainScroll.delegate = self;
    
    mainScroll.scrollEnabled = YES;
   [self.view addSubview:mainScroll];
    
       UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, 10, ScreenWidth, 170)];
    view.backgroundColor=[UIColor whiteColor];
    [mainScroll addSubview:view];
    
    UILabel *lineLabel11111=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.35)];
    lineLabel11111.backgroundColor=qianhuicolor;
    [view addSubview:lineLabel11111];
    UILabel *lineLabel11=[[UILabel alloc] initWithFrame:CGRectMake(0, 170, ScreenWidth, 0.35)];
    lineLabel11.backgroundColor=qianhuicolor;
    [view addSubview:lineLabel11];
    
    
    
    
    mendianimage=[[UIButton alloc]initWithFrame:CGRectMake(15, 10, ScreenWidth-30, 150)];    [mendianimage setBackgroundImage:[UIImage imageNamed:@"tianjiahuodong"] forState:UIControlStateNormal];
    [view addSubview:mendianimage];
    
    UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editPortrait)];
    [mendianimage addGestureRecognizer:portraitTap];
    
    
    UIView* myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:daxiao];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    
    
    
    
    UIView * ZJSwitchview=[[UIView alloc]initWithFrame:CGRectMake(0, view.bottom+10, ScreenWidth, 45)];
    ZJSwitchview.backgroundColor=[UIColor whiteColor];
    [mainScroll addSubview:ZJSwitchview];
    
  
    UILabel *lineLabe111=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.35)];
    lineLabe111.backgroundColor=qianhuicolor;
    [ZJSwitchview addSubview:lineLabe111];
    
    
    UILabel* lingqu=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, 200,45)];
    lingqu.text=[NSString stringWithFormat:@"%@", @"在平台商城中公开领取"];
    lingqu.font=[UIFont systemFontOfSize:contenfot];
    lingqu.textColor=shenhuicolor;
    [ZJSwitchview addSubview:lingqu];
    
    switch2 = [[ZJSwitch alloc] initWithFrame:CGRectMake(ScreenWidth-75, 7, 55, ScreenHeight*15/1334)];
     switch2.on = YES;
    switch2.onTintColor =luseColor;
    [switch2 addTarget:self action:@selector(switchAction1:) forControlEvents:UIControlEventValueChanged];
    [ZJSwitchview addSubview:switch2];
    
    
    UIView * view1=[[UIView alloc]initWithFrame:CGRectMake(0, ZJSwitchview.bottom, ScreenWidth, 490)];
    view1.backgroundColor=[UIColor whiteColor];
    [mainScroll addSubview:view1];
    UILabel *lineLabe1=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.35)];
    lineLabe1.backgroundColor=qianhuicolor;
    [view1 addSubview:lineLabe1];
    //     手势
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoad)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate = self;
    [view1 addGestureRecognizer:singleFingerOne];
   
    UIButton*jiantouBtn3 = [[UIButton alloc]init];
    jiantouBtn3.frame = CGRectMake(ScreenWidth-30,15,8, 13);
    [jiantouBtn3 setImage:[UIImage imageNamed:@"xiangzuo-.png"] forState:UIControlStateNormal];
    [view1 addSubview:jiantouBtn3];
    
    leibieTextFied=[[UITextField alloc]initWithFrame:CGRectMake(15,  0, ScreenWidth*500/750,  45)];
    leibieTextFied.borderStyle = UITextBorderStyleNone;
    leibieTextFied.font = [UIFont systemFontOfSize: contenfot];
    leibieTextFied.textColor=[UIColor blackColor];
    leibieTextFied.autocapitalizationType = UITextAutocapitalizationTypeSentences;
    leibieTextFied.tag=5;
    leibieTextFied.placeholder = @"请选择类别"; //默认显示的字
    [leibieTextFied setUserInteractionEnabled:NO];
    leibieTextFied.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view1 addSubview:leibieTextFied];
    UIButton*leibieBtn=[[UIButton alloc]initWithFrame:CGRectMake(70, 0, ScreenWidth, 45)];
    [leibieBtn addTarget:self action:@selector(leibieBtn:) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:leibieBtn];
    
  
    
    UILabel* baioti=[[UILabel alloc]initWithFrame:CGRectMake(15, 45, 70,45)];
    baioti.text=[NSString stringWithFormat:@"%@", @"活动标题"];
    baioti.font=[UIFont systemFontOfSize:contenfot];
    baioti.textColor=[UIColor blackColor];
    [view1 addSubview:baioti];
    
    titleTextField=[[UITextField alloc]initWithFrame:CGRectMake(baioti.right,45, ScreenWidth*500/750,  45)];
    titleTextField.borderStyle = UITextBorderStyleNone;
    titleTextField.font = [UIFont systemFontOfSize: contenfot];
    titleTextField.textColor=[UIColor blackColor];
    titleTextField.autocapitalizationType = UITextAutocapitalizationTypeSentences;
    titleTextField.tag=1;
    titleTextField.placeholder = @"请输入活动标题"; //默认显示的字
    titleTextField.delegate = self;
    [titleTextField setUserInteractionEnabled:YES];
    titleTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view1 addSubview:titleTextField];
    
    
    
    UILabel*  price=[[UILabel alloc]initWithFrame:CGRectMake(15, 90, 70,45)];
    price.text=[NSString stringWithFormat:@"%@", @"活动地区"];
    price.font=[UIFont systemFontOfSize:contenfot];
    price.textColor=[UIColor blackColor];
    [view1 addSubview: price];
    UIButton*area=[[UIButton alloc]initWithFrame:CGRectMake(price.right, 90, ScreenWidth, 30)];
    [area addTarget:self action:@selector(area:) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:area];

    priceTextFied=[[UITextField alloc]initWithFrame:CGRectMake(price.right,  90, ScreenWidth*500/750,  45)];
    priceTextFied.borderStyle = UITextBorderStyleNone;
    priceTextFied.font = [UIFont systemFontOfSize: contenfot];
    priceTextFied.textColor=[UIColor blackColor];
    priceTextFied.autocapitalizationType = UITextAutocapitalizationTypeSentences;
    priceTextFied.tag=2;
    priceTextFied.placeholder = @"请选择活动地区"; //默认显示的字
    [priceTextFied setUserInteractionEnabled:NO];
    priceTextFied.delegate = self;
    priceTextFied.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view1 addSubview:priceTextFied];

   
    UILabel*  actAddress=[[UILabel alloc]initWithFrame:CGRectMake(15, 135, 70,45)];
    actAddress.text=[NSString stringWithFormat:@"%@", @"活动地址"];
    actAddress.font=[UIFont systemFontOfSize:contenfot];
    actAddress.textColor=[UIColor blackColor];
    [view1 addSubview: actAddress];
   actAddressTextFied=[[UITextField alloc]initWithFrame:CGRectMake( price.right,  135, ScreenWidth*500/750,  45)];
    actAddressTextFied.borderStyle = UITextBorderStyleNone;
    actAddressTextFied.font = [UIFont systemFontOfSize: contenfot];
    actAddressTextFied.textColor=[UIColor blackColor];
    actAddressTextFied.autocapitalizationType = UITextAutocapitalizationTypeSentences;
    actAddressTextFied.tag=3;
    actAddressTextFied.placeholder = @"请现在活动地址"; //默认显示的字
    [actAddressTextFied setUserInteractionEnabled:YES];
    actAddressTextFied.delegate = self;
    actAddressTextFied.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view1 addSubview:actAddressTextFied];

    
    
    
    UILabel* beginDate=[[UILabel alloc]initWithFrame:CGRectMake(15, 180,70,45)];
    beginDate.text=[NSString stringWithFormat:@"%@", @"开始时间"];
    beginDate.font=[UIFont systemFontOfSize:contenfot];
    beginDate.textColor=[UIColor blackColor];
    [view1 addSubview:beginDate];
    UIButton*jiantouBtn= [[UIButton alloc]init];
    jiantouBtn.frame = CGRectMake(ScreenWidth-30,180+15,8, 13);
    [jiantouBtn setImage:[UIImage imageNamed:@"xiangzuo-.png"] forState:UIControlStateNormal];
    [view1 addSubview:jiantouBtn];

    
    openTimeTextFied=[[UITextField alloc]initWithFrame:CGRectMake(beginDate.right,  180, ScreenWidth*530/750,  45)];
    openTimeTextFied.borderStyle = UITextBorderStyleNone;
    openTimeTextFied.font = [UIFont systemFontOfSize: contenfot];
    openTimeTextFied.textColor=[UIColor blackColor];
    openTimeTextFied.autocapitalizationType = UITextAutocapitalizationTypeSentences;
    openTimeTextFied.tag=4;
    openTimeTextFied.placeholder = @"请输入开始时间"; //默认显示的字
    openTimeTextFied.delegate = self;
    [openTimeTextFied setUserInteractionEnabled:YES];
    openTimeTextFied.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view1 addSubview:openTimeTextFied];
    
    UILabel* endDate=[[UILabel alloc]initWithFrame:CGRectMake(15, 225,70,45)];
    endDate.text=[NSString stringWithFormat:@"%@", @"结束时间"];
    endDate.font=[UIFont systemFontOfSize:contenfot];
    endDate.textColor=[UIColor blackColor];
    [view1 addSubview:endDate];
    UIButton*jiantouBtn1= [[UIButton alloc]init];
    jiantouBtn1.frame = CGRectMake(ScreenWidth-30,225+15,8, 13);
    [jiantouBtn1 setImage:[UIImage imageNamed:@"xiangzuo-.png"] forState:UIControlStateNormal];
    [view1 addSubview:jiantouBtn1];
    
    endDateTextFied=[[UITextField alloc]initWithFrame:CGRectMake(endDate.right,  225, ScreenWidth*530/750,  45)];
    endDateTextFied.borderStyle = UITextBorderStyleNone;
    endDateTextFied.font = [UIFont systemFontOfSize: contenfot];
    endDateTextFied.textColor=[UIColor blackColor];
    endDateTextFied.autocapitalizationType = UITextAutocapitalizationTypeSentences;
    endDateTextFied.tag=5;
    endDateTextFied.placeholder = @"请输入结束时间"; //默认显示的字
    endDateTextFied.delegate = self;
    [endDateTextFied setUserInteractionEnabled:YES];
    endDateTextFied.clearButtonMode = UITextFieldViewModeWhileEditing;
    [view1 addSubview:endDateTextFied];
    [_da setAccessibilityLanguage:@"Chinese"];
    
    openTimeTextFied.inputView = _da;
    endDateTextFied.inputView = _da;
    
    UIView*diview=[[UIView alloc]initWithFrame:CGRectMake(0, endDateTextFied.bottom, ScreenWidth, 10)];
    diview.backgroundColor=zuiqianhuicolor;
    [view1 addSubview:diview];
    UILabel *line911=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.35)];
    line911.backgroundColor=qianhuicolor;
    [diview addSubview:line911];
    UILabel *line91=[[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 0.35)];
    line91.backgroundColor=qianhuicolor;
    [diview addSubview:line91];
    
    
    tv=[[UITextView alloc]init];
    tv.frame=CGRectMake(15, endDateTextFied.bottom+20, ScreenWidth-30, 80);
    tv.backgroundColor = [UIColor whiteColor];//设置它的背景颜色/Users/jiezsoft/Desktop/
    tv.scrollEnabled = YES;//是否可以拖动
    tv.delegate=self;
    tv.font = [UIFont fontWithName:@"Arial" size:15.0];//设置字体名字和字体大小
    tv.layer.borderWidth =0;
    CGColorSpaceRef registedSpace11 = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref111 = CGColorCreate(registedSpace11,(CGFloat[]){ 0, 0, 0, 0.3 });
    //                tv.keyboardType = UIKeyboardTypePhonePad;
    [tv.layer setBorderColor:tureBTncolorref111];//边框颜色
    tv.layer.cornerRadius =0;
    [view1 addSubview:tv];
    imagess=[[UIImageView alloc]initWithFrame:CGRectMake(5, 10, 51/3, 51/3)];
    imagess.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
    [tv addSubview:imagess];
    labels=[[UILabel alloc]init];
    labels.frame =CGRectMake(28, 11, ScreenWidth-60, 15);
    labels.text = @"活动详情描述";
    labels.textColor=qianhuicolor;
    labels.numberOfLines=0;
    labels.font=[UIFont systemFontOfSize:15];
    [tv addSubview:labels];
    
    UILabel *line1 = [[UILabel alloc]initWithFrame:CGRectMake(15,0, ScreenWidth-30, 0.35)];
    line1.backgroundColor = labelColor;
    //  [view1 addSubview:line1];
    UILabel *line11 = [[UILabel alloc]initWithFrame:CGRectMake(15,45, ScreenWidth-30, 0.35)];
    line11.backgroundColor = labelColor;
    [view1 addSubview:line11];
    UILabel *line111 = [[UILabel alloc]initWithFrame:CGRectMake(15,90, ScreenWidth-30, 0.35)];
    line111.backgroundColor = labelColor;
    [view1 addSubview:line111];
    UILabel *line1111 = [[UILabel alloc]initWithFrame:CGRectMake(15,135, ScreenWidth-30, 0.35)];
    line1111.backgroundColor = labelColor;
    [view1 addSubview:line1111];
    UILabel *line12 = [[UILabel alloc]initWithFrame:CGRectMake(15,180, ScreenWidth-30, 0.35)];
    line12.backgroundColor = labelColor;
    [view1 addSubview:line12];
    UILabel *line13 = [[UILabel alloc]initWithFrame:CGRectMake(15,225, ScreenWidth-30, 0.35)];
    line13.backgroundColor = labelColor;
    [view1 addSubview:line13];
    UILabel *line14 = [[UILabel alloc]initWithFrame:CGRectMake(15,270, ScreenWidth-30, 0.35)];
    line14.backgroundColor = labelColor;
    [view1 addSubview:line14];

        
    UIView*actview1=[[UIView alloc]initWithFrame:CGRectMake(0, tv.bottom+10, ScreenWidth, 10)];
    actview1.backgroundColor=zuiqianhuicolor;
    [view1 addSubview:actview1];
    UILabel *lineLabs=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.35)];
    lineLabs.backgroundColor=qianhuicolor;
    [actview1 addSubview:lineLabs];
    UILabel *lineLab1s=[[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 0.35)];
    lineLab1s.backgroundColor=qianhuicolor;
    [actview1 addSubview:lineLab1s];
    
   imageArray = [NSMutableArray arrayWithObjects:nil];
    imageList= [[NSMutableArray alloc]init];
//    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
//    //设置单元格的尺寸
//    flowLayout.itemSize = CGSizeMake(collectionCellHeight, collectionCellHeight);
//    
//    flowLayout.minimumInteritemSpacing = 5;
//    flowLayout.minimumLineSpacing = 5;
//    flowLayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15);
//    
//    
//    UILabel* BirthDate1=[[UILabel alloc]initWithFrame:CGRectMake(15, actview1.bottom, ScreenWidth*220/750,45)];
//    BirthDate1.text=[NSString stringWithFormat:@"%@", @"添加活动图片"];
//    BirthDate1.font=[UIFont systemFontOfSize:15];
//    BirthDate1.textColor=[UIColor blackColor];
//    [view1 addSubview:BirthDate1];
//    
//    UILabel* BirthDate=[[UILabel alloc]initWithFrame:CGRectMake(BirthDate1.right,  actview1.bottom, 170,45)];
//    BirthDate.text=[NSString stringWithFormat:@"%@", @"(多选)"];
//    BirthDate.font=[UIFont systemFontOfSize:15];
//    BirthDate.textColor=qianhuicolor;
//    [view1 addSubview:BirthDate];
//    
//    UIImageView *_xianview1 = [[UIImageView alloc]initWithFrame:CGRectMake(15,BirthDate.bottom-0.35, ScreenWidth-30, 0.5)];
//    _xianview1.image=[UIImage imageNamed:@"hengxian"];
//    [view1 addSubview:_xianview1];
//
//    
//    
//    
//    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0,view1.bottom, ScreenWidth, collectionCellHeight*4+25*2) collectionViewLayout:flowLayout];
//    _collectionView.backgroundColor = [UIColor whiteColor];
//   _collectionView.dataSource=self;
//    _collectionView.delegate=self;
//     _collectionView.alwaysBounceVertical = YES;
//    [_collectionView registerClass:[webCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
//    
//
//    
//  [mainScroll addSubview:_collectionView];

    
    closeTimeTextFied.inputAccessoryView = myToolBar;
    openTimeTextFied.inputAccessoryView = myToolBar;
    titleTextField.inputAccessoryView = myToolBar;
    urlTextField.inputAccessoryView = myToolBar;
    actAddressTextFied.inputAccessoryView = myToolBar;
    priceTextFied.inputAccessoryView = myToolBar;
    endDateTextFied.inputAccessoryView = myToolBar;
    urlTextField.inputAccessoryView = myToolBar;
    tv.inputAccessoryView = myToolBar;
   
   
    
   [mainScroll setContentSize:CGSizeMake(ScreenWidth, ScreenHeight)];
    
}

-(void)switchAction1:(UISwitch*)sender{
    
    if (sender.on ==YES) {
        
        isOpen=@"1";
        
        
    }
    
    if (sender.on == NO) {
        isOpen=@"0";
        
    }
}

//上传数据
-(void)add:(UIButton*)sender{
    [imageList removeAllObjects];
    [self  upToUpYun];
    
}


-(void)upToUpYun
{
    
    
    if ([ titleTextField.text length] < 1)
    {
        [self showAlertMessage:@"请输入活动标题"];
    }
    else
    {
        if ([priceTextFied.text length] <1)
        {
            [self showAlertMessage:@"请现在活动地区"];
        }
        else{
            if ([leibieTextFied.text length] <1)
            {
                [self showAlertMessage:@"请选择活动类别"];
            }else {
                if ([tv.text length] <1)
                {
                    [self showAlertMessage:@"请输入活动详情"];
                }
                else{
                    if (imageArray.count ==0)
                    {
                        
                        [imageList removeAllObjects];
                        [self  baocunxia];
                        
                        
                        
                        
                    }
                    else{

                    

    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:20 view:self.view];
    for (int i=0; i<imageArray.count; i++) {
        
        UIImage *portraitImg = [[UIImage alloc]init];
        portraitImg = [self imageByScalingToMaxSize:imageArray[i]];
       
        
        UpYun *uy = [[UpYun alloc] init];
        uy.successBlocker = ^(id data)
        {
            
            [Global hideProgressHUDInternal:self.view];
            NSString *imageURL;
            NSString *imageWIDTH;
            NSString *imageHEIGHT;
            imageURL=[data objectForKey:@"url"];
            imageWIDTH=[data objectForKey:@"image-width"];
            imageHEIGHT=[data objectForKey:@"image-height"];
            NSMutableDictionary *upYunImageDict=[NSMutableDictionary dictionary];
            [upYunImageDict setObject:imageURL forKey:@"imageUrl"];
            [upYunImageDict setObject:imageWIDTH forKey:@"imageWidth"];
            [upYunImageDict setObject:imageHEIGHT forKey:@"imageHeight"];
            
            [imageList addObject:upYunImageDict];
            

            if (imageList.count==imageArray.count) {
                
                [Global hideProgressHUDInternal:self.view];
                NSLog(@"--------－－－－%@",imageList);
                [self  baocunxia];
            }
            
        };
        uy.failBlocker = ^(NSError * error)
        {
            [Global hideProgressHUDInternal:self.view];
            
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"上传失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            NSLog(@"%@",error);
        };
        uy.progressBlocker = ^(CGFloat percent, long long requestDidSendBytes)
        {
            
        };
        
        [uy uploadFile:portraitImg saveKey:[self getSaveKey]];
        
       
        
    }}}}

}}
}
-(void)baocunxia{
    
    
    
    
    
                    
                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                    NSString* tokenId = [user objectForKey:@"tokenId"];
                    
                    NSMutableDictionary *params = [NSMutableDictionary new];
                    
                    [params setValue:[NSString stringWithFormat:@"%@",tokenId] forKey:@"tokenId"];
                    [params setValue:@"A" forKey:@"editType"];
                    [params setValue:titleTextField.text forKey:@"actName"];
                    [params setValue:commdity.actTypeCode forKey:@"actTypeCode"];
                    [params setValue:isOpen forKey:@"isOpen"];
                    [params setValue:self.companyImg forKey:@"imageUrl"];
                    [params setValue:self.companyImgWidth forKey:@"imageWidth"];
                    [params setValue:self.companyImgHeight forKey:@"imageHeight"];
                    
                    [params setValue:priceTextFied.text  forKey:@"actRegion"];
                    [params setValue:actAddressTextFied.text  forKey:@"actAddress"];
                    
                   
                    [params setValue:tv.text  forKey:@"actDetail"];
                    
                    [params setValue:openTimeTextFied.text  forKey:@"beginDate"];
                    [params setValue:endDateTextFied.text  forKey:@"endDate"];
                    
                    NSLog(@"33333333====%@",params);
                    [params setValue:imageList  forKey:@"imageList"];
                    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:20 view:self.view];
                    
                    
                    [HttpRequest requestData:@"Business/Act/Edit" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                        if (isSuccess) {
                            
                            NSLog(@"33333333====%@",severDataDict.dataDict);
                            
                            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                                [Global hideProgressHUDInternal:self.view];
                                
                                
                                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                                [Global showTextHudSub:requestResultStr view:self.view];
                                [self.navigationController popViewControllerAnimated:YES];
//                                    commdity.Dictss=nil;
                                
                                
                            }else{
                                   [Global hideProgressHUDInternal:self.view];
                                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                                
                                [Global showTextHudSub:requestResultStr view:self.view];
                            }
                            
                        }
                        else
                        {
                            [Global hideProgressHUDInternal:self.view];
                            
                            [Global showTextHudSub:@"连接失败" view:self.view];
                        }
                        
                    }];
                    
               }




- (void)userNumberLimitTextLength:(UITextField*)textField
{
    if ([textField.text length] > 11)
    {
        textField.text = [textField.text substringToIndex:11];
    }
}

-(void)chooseBtn:(id)sender
{
    saveAccount=!saveAccount;
    if (saveAccount) {
        //        [chooseBtn setImage:[UIImage imageNamed:@"_0000_yixuanzhe.png"] forState:UIControlStateNormal];
        agreementBtn. backgroundColor=luseColor;
    }
    else
    {
        //        [chooseBtn setImage:[UIImage imageNamed:@"_0001_weigouxuan.png"] forState:UIControlStateNormal];
        agreementBtn. backgroundColor=nil;
    }
    
}
- (void)dateChanged:(id)sender
{
    UIDatePicker* picker = (UIDatePicker*)sender;
    NSDateFormatter* df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
  
    
    double time1;
    double time2;
    
    if ([openTimeTextFied isFirstResponder])
    {
        openTimeTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        
        
        NSString* string2 = openTimeTextFied.text;
        NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
        [dateFormatter2 setDateFormat: @"yyyy-MM-dd "];
        NSDate *destDate2= [dateFormatter2 dateFromString:string2];
        NSTimeInterval  timeInterval1 = [destDate2 timeIntervalSinceDate:[NSDate date]];
        
        NSString* string = endDateTextFied.text;
        NSDateFormatter *dateFormatter3 = [[NSDateFormatter alloc] init];
        [dateFormatter3 setDateFormat: @"yyyy-MM-dd "];
        NSDate *destDate3= [dateFormatter3 dateFromString:string];
        NSTimeInterval  timeInterval2 = [destDate3 timeIntervalSinceDate:[NSDate date]];
        
        
        time1=timeInterval1;
        time2=timeInterval2;
        NSLog(@"%.f",time1);
        NSLog(@"%.f",time2);
        if (time1<=0 ) {
            openTimeTextFied.text=nil;
            [self showAlertMessage:@"开始日期必须大于当前日期"];
        }
        
        if (time2==0) {
        }else{
            
            if (time1>=time2 ) {
                endDateTextFied.text=nil;
                [self showAlertMessage:@"结束日期必须大于或等于开始日期"];
            }
        }
    }else{
        
        
        
        endDateTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:picker.date]];
        
        NSString* string2 = endDateTextFied.text;
        NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];
        [dateFormatter2 setDateFormat: @"yyyy-MM-dd "];
        NSDate *destDate2= [dateFormatter2 dateFromString:string2];
        NSTimeInterval  timeInterval2 = [destDate2 timeIntervalSinceDate:[NSDate date]];
        
        time2=timeInterval2;
        if (time1>=time2 ) {
            endDateTextFied.text=nil;
            [self showAlertMessage:@"结束日期必须大于或等于开始日期"];
        }
        
        
    }
    
    
    
    
}

-(void)textViewDidChange:(UITextView *)textView
{
     [self cancelLocatePicker];
    if (textView.text.length == 0) {
        [imagess removeFromSuperview];
        
        imagess=[[UIImageView alloc]initWithFrame:CGRectMake(5, 10, 51/3, 51/3)];
        imagess.image=[UIImage imageNamed:@"_0000_xingxifankui.png"];
        [tv addSubview:imagess];
          labels.text = @"活动详情描述";
        
    }else{
        [imagess removeFromSuperview];
          labels.text = @"";
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField{

    if (textField.tag == 4)
    {
        if ([openTimeTextFied.text length]>0) {
            
        }else{
            NSDateFormatter* df = [[NSDateFormatter alloc] init];
            [df setDateFormat:@"yyyy-MM-dd "];
            
            
            openTimeTextFied.text = [NSString stringWithFormat:@"%@", [df stringFromDate:[NSDate date]]];
        }

    
    
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
       [self cancelLocatePicker];
    if (textField.tag == 1)
    { [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        mainScroll .frame =CGRectMake(0, -10, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        
        
    }
    if (textField.tag == 2)
    { [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        mainScroll .frame =CGRectMake(0, -50, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        
        
    }
    
    if (textField.tag == 3)
    { [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        mainScroll .frame =CGRectMake(0, -150, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        
        
    }
    
    if (textField.tag == 4)
    {
        
        
        
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        mainScroll .frame =CGRectMake(0, -150, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        
        
    }
    
    if (textField.tag == 5)
    { [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        mainScroll .frame =CGRectMake(0, -150, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        
        
    }
    if (textField.tag == 9)
    { [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        mainScroll .frame =CGRectMake(0, -350, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
        
        
    }
    
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    mainScroll .frame =CGRectMake(0, -250, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
    
    
    
    return self;
}

-(void)OnTapDone{
    
    
    [closeTimeTextFied resignFirstResponder];
    [openTimeTextFied resignFirstResponder];
    [titleTextField resignFirstResponder];
    [AddressTextFied resignFirstResponder];
    [priceTextFied resignFirstResponder];
    
    [tv resignFirstResponder];
    [actAddressTextFied resignFirstResponder];
    [urlTextField resignFirstResponder];
    [endDateTextFied resignFirstResponder];
      [self cancelLocatePicker];
    
   
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    mainScroll .frame =CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
    
    
    
}

-(void)closeKeyBoad
{
    
    [closeTimeTextFied resignFirstResponder];
    [openTimeTextFied resignFirstResponder];
    [titleTextField resignFirstResponder];
 
    [AddressTextFied resignFirstResponder];
    [priceTextFied resignFirstResponder];
    
    [tv resignFirstResponder];
    [actAddressTextFied resignFirstResponder];
    [urlTextField resignFirstResponder];
    [endDateTextFied resignFirstResponder];
    
    
      [self cancelLocatePicker];
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    mainScroll .frame =CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [UIView commitAnimations];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark portraitImageView getter


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return imageArray.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * string = @"cell";
    webCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:string forIndexPath:indexPath];
    
    if (indexPath.row == imageArray.count) {
        cell.imgView.image = [UIImage imageNamed:@"tianjiatupain"];
    }else{
        cell.imgView.image = imageArray[indexPath.row];
    }
    

    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.sat =@"bubiaoti";

        if (indexPath.item == imageArray.count)
        {
            UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
            [actionSheet showInView:self.view];
        }
        else
        {
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"确定删除" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alertView.tag = indexPath.row;
            [alertView show];
        }

        [self.collectionView reloadData];

}


- (void)editPortrait {
    
    
    self.sat=nil;
    self.sat=@"biaoti";
    
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate


#pragma mark UIActionSheetDelegate

- (void)showCamera
{
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    controller.delegate = self;
    controller.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        if (self.popover.isPopoverVisible) {
            [self.popover dismissPopoverAnimated:NO];
        }
        
        self.popover = [[UIPopoverController alloc] initWithContentViewController:controller];
        
    } else {
        [self presentViewController:controller animated:YES completion:NULL];
    }
}

- (void)openPhotoAlbum
{
    UIImagePickerController *controller = [[UIImagePickerController alloc] init];
    controller.delegate = self;
    controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        if (self.popover.isPopoverVisible) {
            [self.popover dismissPopoverAnimated:NO];
        }
        
        self.popover = [[UIPopoverController alloc] initWithContentViewController:controller];
        
    } else {
        [self presentViewController:controller animated:YES completion:NULL];
    }
}





- (void)openEditor
{
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = image1;
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
        navigationController.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    
    [self presentViewController:navigationController animated:YES completion:NULL];
}

- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage
{
    [controller dismissViewControllerAnimated:YES completion:NULL];
    [mendianimage setBackgroundImage:croppedImage forState:UIControlStateNormal];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:mainScroll];
//    UIImage *headPortraitImage=[self imageCompress:croppedImage];
    
    UIImage *portraitImg = [[UIImage alloc]init];
    portraitImg = [self imageByScalingToMaxSize:croppedImage];
    UpYun *uy = [[UpYun alloc] init];
    uy.successBlocker = ^(id data)
    {
        
        NSLog(@"－－－－－－－－－%@",[data objectForKey:@"url"]);
        [Global hideProgressHUDInternal:mainScroll];
        self.companyImg=[data objectForKey:@"url"];
        self.companyImgHeight=[NSString stringWithFormat:@"%@",[data objectForKey:@"image-height"]];
        self.companyImgWidth=[NSString stringWithFormat:@"%@",[data objectForKey:@"image-width"]];
        
 
    };
    uy.failBlocker = ^(NSError * error)
    {
        [Global hideProgressHUDInternal:mainScroll];
        
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"上传失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        NSLog(@"%@",error);
    };
    uy.progressBlocker = ^(CGFloat percent, long long requestDidSendBytes)
    {
        
    };
    
    
    [uy uploadFile:portraitImg saveKey:[self getSaveKey]];

    
}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller
{
    [controller dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    
    if ([self.sat isEqualToString:@"biaoti"]) {
    
    if (buttonIndex == 0) {
        [self showCamera];
    }
    
    if (buttonIndex == 1) {
        [self openPhotoAlbum];
    }
    }else{
    
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            controller.cameraDevice = UIImagePickerControllerCameraDeviceRear;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            controller.allowsEditing = YES;
//            controller.allowsImageEditing=YES;
//         controller.showsCameraControls=true;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
//            controller.allowsImageEditing=YES;
             controller.allowsEditing = YES;
//            controller.showsCameraControls=NO;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                                 NSLog(@"Picker View Controller is presented");
                             }];
        }
    }}
}




- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 1)
    {
        
        [imageArray removeObjectAtIndex:alertView.tag];
        [self.collectionView reloadData];

        
    }

    
    
}




- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
 
    
    if ([self.sat isEqualToString:@"biaoti"]) {
   
        
        
        image1 = info[UIImagePickerControllerOriginalImage];
        
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            if (self.popover.isPopoverVisible) {
                [self.popover dismissPopoverAnimated:NO];
            }
            
            [self openEditor];
        } else {
            [picker dismissViewControllerAnimated:YES completion:^{
                [self openEditor];
            }];
        }

        

        
        
    
    }else{
           
            UIImage* image11 = [info valueForKey:UIImagePickerControllerEditedImage];
            if (image11 != nil)
            {
 
            
            [imageArray addObject:image11];
            [self.collectionView reloadData];
            [picker dismissViewControllerAnimated:YES completion:nil];
       
        }
        
       
        
    }
    
    
    
   
}













- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
}

#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return nil;
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}
#define ORIGINAL_MAX_WIDTH 420.0f
#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}


-(NSString * )getSaveKey {
    /**
     *	@brief	方式1 由开发者生成saveKey
     */
    NSDate *d = [NSDate date];
    return [NSString stringWithFormat:@"/%d/%d/%.0f.png",[self getYear:d],[self getMonth:d],[[NSDate date] timeIntervalSince1970]];
    
    /**
     *	@brief	方式2 由服务器生成saveKey
     */
    //    return [NSString stringWithFormat:@"/{year}/{mon}/{filename}{.suffix}"];
    
    /**
     *	@brief	更多方式 参阅 http://wiki.upyun.com/index.php?title=Policy_%E5%86%85%E5%AE%B9%E8%AF%A6%E8%A7%A3
     */
    
}

- (int)getYear:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int year=[comps year];
    return year;
}

- (int)getMonth:(NSDate *) date{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSMonthCalendarUnit;
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    int month = [comps month];
    return month;
}
-(UIImage *)imageCompress:(UIImage *)image11
{
    UIImage *comImage=image11;
    NSData * sendImageData = UIImageJPEGRepresentation(comImage, 1.0);
    NSUInteger sizeOrigin = [sendImageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    
    if (sizeOriginKB >400) {
        float a = 800.0000;
        float b = (float)sizeOriginKB;
        float q = sqrtf(a / b);
        
        CGSize sizeImage = [comImage size];
        CGFloat widthSmall = sizeImage.width * q;
        CGFloat heighSmall = sizeImage.height * q;
        CGSize sizeImageSmall = CGSizeMake(widthSmall, heighSmall);
        
        UIGraphicsBeginImageContext(sizeImageSmall);
        CGRect smallImageRect = CGRectMake(0, 0, sizeImageSmall.width, sizeImageSmall.height);
        [image drawInRect:smallImageRect];
        UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        NSData *dataImage = UIImageJPEGRepresentation(smallImage, 1.0);
        sendImageData = dataImage;
        NSLog(@"11111111%f",sizeImageSmall.width);
        NSLog(@"11111111%f",sizeImageSmall.height);
        comImage= smallImage;
        // [_imageview1.image retain];
    }
    return comImage;
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:2.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:2.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
-(void)leibieBtn:(UIButton*)sender{
      [self cancelLocatePicker];
    actlistsViewController *detailViewController = [[actlistsViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];
}


@end